import { message, Modal, Table } from 'antd';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import roleService from '@/api/services/security/roleService';
import { hasPermission } from '@/utils/permission';

import { ListData, Role } from '#/entity';

type RoleModalProps = {
  show: boolean;
  onOk: () => void;
  onCancel: () => void;
  formValue: any;
};

export function RoleModal({ show, onOk, onCancel, formValue }: RoleModalProps) {
  const [roleData, setRoleData] = useState<ListData<Role>>();
  useEffect(() => {
    // 获取所有的角色列表
    if (hasPermission('SECURITY:ROLE:READ')) {
      roleService
        .getRoleList({
          take: 100,
          page: 1,
        })
        .then((res) => setRoleData(res));
    }
  }, []);
  useEffect(() => {
    // 初始化选中的角色列表
    if (formValue.roles) {
      setSelectedRowKeys(
        formValue.roles.map((item: { id: number }) => {
          return item.id;
        }),
      );
    }
  }, [formValue]);
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
  ];
  // 选中的角色列表
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<Role> = {
    hideSelectAll: true,
    selectedRowKeys,
    onChange: onSelectChange,
    onSelect: (record: Role, selected: boolean) => {
      if (selected) {
        roleService.userAddRole(record.id, formValue.id).then((res) => {
          if (res > 0) {
            message.success(`为用户 ${formValue.name || ''} 添加 ${record.name} 成功`);
            onCancel();
          }
        });
      } else {
        roleService.userDeleteRole(record.id, formValue?.id || 0).then((res) => {
          if (res > 0) {
            message.success(`为用户 ${formValue?.name || ''} 删除 ${record.name} 成功`);
            onCancel();
          }
        });
      }
    },
  };
  return (
    <Modal
      cancelText="关闭"
      title={`为用户 ${formValue.name || ''} 分配角色`}
      open={show}
      onOk={onOk}
      onCancel={onCancel} // 隐藏取消按钮,但是保留取消功能
      okButtonProps={{ style: { display: 'none' } }}

      maskClosable
      keyboard
    >
      <Table
        rowKey="id"
        rowSelection={rowSelection}
        dataSource={roleData?.data}
        columns={columns}
        size="small"
      />
    </Modal>
  );
}
